<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Audio Cutter</title>

        <link href="data:image/gif;" rel="icon" type="image/x-icon" />

        <!-- Bootstrap -->
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet">

        <link rel="stylesheet" href="./example/css/style.css" />
        <link rel="stylesheet" href="./example/css/ribbon.css" />
        <link rel="screenshot" itemprop="screenshot" href="https://katspaugh.github.io/wavesurfer.js/example/screenshot.png" />

        <!-- wavesurfer.js -->
        <script src="https://cdn.bootcdn.net/ajax/libs/wavesurfer.js/4.2.0/wavesurfer.min.js"></script>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>

        <!-- plugins -->
        <script src="./dist/plugin/wavesurfer.timeline.js"></script>
        <script src="./dist/plugin/wavesurfer.regions.js"></script>
        <script src="./dist/plugin/wavesurfer.minimap.js"></script>
        <script src="./dist/plugin/wavesurfer.elan.js"></script>

        <!-- App -->
        <script src="./example/trivia.js"></script>
    </head>

    <body itemscope itemtype="http://schema.org/WebApplication">
        <div class="container">
            <div class="header">
                <ul class="nav nav-pills pull-right">
                    <form>
                        <li><input id="file" type="file" onchange="getFile(this)"></li>
                    </form>
                </ul>

                <!-- <h1 itemprop="name" id="filename">File Name</h1> -->
            </div>

            <div id="demo">
                <div id="waveform">
                    <!-- Here be waveform -->
                </div>
                <div id="annotations" class="table-responsive">
                    <!-- Here be transcript -->
                </div>
                
                <div id="number" style="text-align: center;">分割了0段</div>
                <div class="controls">
                    <button class="btn btn-primary" data-action="play">
                        <i class="glyphicon glyphicon-play"></i>
                        Play
                    </button>

                    <button class="btn btn-primary" data-action="pause">
                        <i class="glyphicon glyphicon-pause"></i>
                        Pause
                    </button>

                    <button class="btn btn-success" data-action="cut">
                        <i class="glyphicon glyphicon-pause"></i>
                        Cuuuuuuut!
                    </button>

                    <!-- <button class="btn btn-primary" data-action="show">
                        <i class="glyphicon glyphicon-pause"></i>
                        Show
                    </button> -->
                </div>
                <div style="text-align: center;"><a id="download" class="btn btn-primary" href="">下载</a></div>
            </div>

        <script>
            'use strict';

            var arrBuffer;
            var audioBuffer;

            // Create an instance
            // let wavesurfer;

            // Init & load audio file
            document.addEventListener('DOMContentLoaded', function() {

                // Init
                wavesurfer = WaveSurfer.create({
                    container: document.querySelector('#waveform'),
                    waveColor: '#A8DBA8',
                    progressColor: '#3B8686',
                    backend: 'MediaElement',
                    plugins: [
                        WaveSurfer.regions.create({
                            dragSelection: {
                                slop: 5
                            }
                        })
                    ]
                });


                wavesurfer.on('error', function(e) {
                    console.warn(e);
                });

                wavesurfer.on('region-click', function(e) {
                    // console.log(e)
                    document.onkeydown = function(){
                        var oEvent = window.event;
                        if (oEvent.keyCode == 8 || oEvent.keyCode == 46) {
                            e.remove()
                            document.getElementById("number").innerHTML = "分割了"+Object.keys(wavesurfer.regions.list).length+"段";
                        }}
                });

                wavesurfer.on('region-created', function(e) {
                    console.log(e);                    
                })

                wavesurfer.on('region-dblclick', function(e) {
                    console.log(e.start, e.end);
                    // wavesurfer.play(e.start, e.end);
                })

                wavesurfer.on('region-update-end', function(e) {
                    console.log(wavesurfer.regions.list.length)
                    document.getElementById("number").innerHTML = "分割了"+Object.keys(wavesurfer.regions.list).length+"段";
                })

                // Load audio from URL
                // wavesurfer.load("C:\fakepath\1-54 The Pet Shop.mp3");
                
                document.querySelector(
                    '[data-action="play"]'
                ).addEventListener('click', function() {
                    wavesurfer.play();
                });

                document.querySelector(
                    '[data-action="pause"]'
                ).addEventListener('click', function() {
                    wavesurfer.pause();
                });

                //Cut
                document.querySelector(
                    '[data-action="cut"]'
                ).addEventListener('click', function() {
                    // console.log($('#file')[0].files, '---')
                    
                    var crowd_name = $.trim($('#file').val());
                    var crowd_name = crowd_name.replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi,"$1");
                    var crowd_file = $('#file')[0].files[0];

                    var formData = new FormData();

                    let rgArr = [];
                    console.log(wavesurfer.regions.list)
                    for(let k in wavesurfer.regions.list) {
                        let start = wavesurfer.regions.list[k].start.toFixed(2);
                        let offset = (wavesurfer.regions.list[k].end - start).toFixed(2);
                        // let val = {start: start, end: end};
                        let val = [start, offset];
                        rgArr.push(val);
                    }

                    rgArr = JSON.stringify(rgArr);

                    formData.append("file", crowd_file);
                    formData.append("name", crowd_name);
                    formData.append("regions", rgArr);

                    $.ajax({
                        url:'/upload.php',
                        dataType:'json',
                        type:'POST',
                        async: false,
                        data: formData,
                        processData : false, // 使数据不做处理
                        contentType : false, // 不要设置Content-Type请求头
                        success: function(data){
                            console.log(data);
                            if (data.code == 0) {
                                alert('上传成功！');
                                $("#download").show();
                                $("#download").attr('href', data.msg);
                            }

                        },
                        error:function(response){
                            console.log(response);
                        }
                    });

                    


                    //前端实现 非常麻烦，暂时放弃，改到后端处理
                    // var reader = new FileReader();
                    // reader.onload = function (event) {
                    //     var arrBuffer = event.target.result;
                    //     // arrBuffer就是包含音频数据的ArrayBuffer对象

                    //     var audioCtx = new AudioContext();

                    //     audioCtx.decodeAudioData(arrBuffer, function(audioBuffer) {
                    //     // audioBuffer就是AudioBuffer
                    //         // 声道数量和采样率
                    //         var channels = audioBuffer.numberOfChannels;
                    //         var rate = audioBuffer.sampleRate;

                    //         // 截取前3秒
                    //         var startOffset = rate * 1;
                    //         var endOffset = rate * 3;
                    //         // 3秒对应的帧数
                    //         var frameCount = endOffset - startOffset;console.log(rate, frameCount)

                    //         // 创建同样采用率、同样声道数量，长度是前3秒的空的AudioBuffer
                    //         var newAudioBuffer = new AudioContext().createBuffer(channels, endOffset - startOffset, rate);
                    //         // 创建临时的Array存放复制的buffer数据
                    //         var anotherArray = new Float32Array(frameCount);
                    //         // 声道的数据的复制和写入
                    //         var offset = 0;
                    //         for (var channel = 0; channel < channels; channel++) {
                    //             audioBuffer.copyFromChannel(anotherArray, channel, startOffset);
                    //             newAudioBuffer.copyToChannel(anotherArray, channel, offset);
                    //         }

                    //         // newAudioBuffer就是全新的复制的3秒长度的AudioBuffer对象

                    //         // 创建AudioBufferSourceNode对象
                    //         var source = audioCtx.createBufferSource();
                    //         // 设置AudioBufferSourceNode对象的buffer为复制的3秒AudioBuffer对象
                    //         source.buffer = newAudioBuffer;
                    //         // 这一句是必须的，表示结束，没有这一句没法播放，没有声音
                    //         // 这里直接结束，实际上可以对结束做一些特效处理
                    //         source.connect(audioCtx.destination);
                    //         // 资源开始播放
                    //         source.start();
                    //     });
                    // };
                    // reader.readAsArrayBuffer(document.getElementById("file").files[0]);
                });

                // document.querySelector(
                //     '[data-action="show"]'
                // ).addEventListener('click', function() {
                //     console.log(wavesurfer.regions);
                // });
            });
            
            function getFile(obj){
                console.log(obj.files[0]);
                // wavesurfer.loadBlob('./x.mp3')
                var audioReader = new FileReader();
                audioReader.readAsDataURL(obj.files[0]);
                audioReader.onloadend = (f)=>{

                    $("#download").hide();
                    document.getElementById("number").innerHTML = "分割了0段";
                    console.log(f)
                    // console.log(typeof(f.target.result))
                    // let bb = new Blob([f.target.result], {
                    //     type: 'audio/mpeg'
                    // });
                    // let xx = URL.createObjectURL(bb);
                    // console.log(xx);
                    wavesurfer.clearRegions();
                    wavesurfer.load(f.target.result);
                }

                

                console.log(audioReader.result)
                // audioReader.readAsBinaryString(obj.files[0]);//console.log(audioReader);
                // audioReader.onloadend = (f)=>{
                //     console.log(typeof(f.target.result))
                //     let bb = new Blob([f.target.result], {
                //         type: 'audio/mpeg'
                //     });
                //     let xx = URL.createObjectURL(bb);
                //     console.log(xx);
                //     wavesurfer.load(xx);
                // }

                // wavesurfer.loadBlob(obj.files[0]);
            }

            </script>
    </body>
</html>